<script setup lang="ts">
import { nextTick, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { message, QRCode, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import html2canvas from 'html2canvas';

import { useVbenForm } from '#/adapter/form';
import { sourceTrackInfo } from '#/api/register/track';
import { downloadImage } from '#/utils/file/download';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { getMiniProQrcode } from '#/utils/wechat';
// const emit = defineEmits<{ reload: [] }>();

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: [
    {
      component: 'RegisterTrackSelect',
      fieldName: 'sourceTrackId',
      label: '追踪来源',
      componentProps: {
        number: 27,
        onChange: () => {
          reset();
        },
      },
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const bgImgeUrl = ref<string>('');
const qrcodeUrl = ref<string>('');
const miniProQrcodeUrl = ref<string>('');
const posterImgUrl = ref<string>('');
const captureRef = ref<HTMLElement | null>(null);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[640px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { imgUrl } = modalApi.getData() as {
      imgUrl: string;
    };
    bgImgeUrl.value = imgUrl;
    // if (isUpdate.value && id) {
    //   const record = await questionOptionInfo(id);
    //   if (record.labels?.length > 0) {
    //     record.labelIds = record.labels.map((v: any) => v.id);
    //   }
    //   await formApi.setValues(record);
    // }
    markInitialized();

    modalApi.modalLoading(false);
  },
});

const loading = ref<boolean>(false);
const currTrackInfo = ref<any>({});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    loading.value = true;
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // formApi.getValues拿到的是一个readonly对象，不能直接修改，需要cloneDeep
    const data = cloneDeep(await formApi.getValues());
    try {
      const trackInfo = await sourceTrackInfo(data.sourceTrackId);
      console.log('trackInfo', trackInfo);
      if (trackInfo) {
        currTrackInfo.value = trackInfo;
        if (trackInfo.urlType === 1) {
          // 网址链接，生成普通二维码
          qrcodeUrl.value = trackInfo.newUrl;
        }
        if (trackInfo.urlType === 2) {
          // 小程序链接，生成小程序码
          miniProQrcodeUrl.value = await getMiniProQrcode(
            trackInfo.appId as string,
            trackInfo.newUrl,
            310,
          );
          console.log('miniProQrcodeUrl', miniProQrcodeUrl.value);
        }
        await nextTick();
        if (!captureRef.value) return;

        const canvas = await html2canvas(captureRef.value, {
          backgroundColor: '#fff', // 背景色（防止透明）
          scale: 2, // 提高清晰度
          useCORS: true, // 若有外链图片需启用跨域
        });
        // 转为 base64 图片
        posterImgUrl.value = canvas.toDataURL('image/png');
        await downloadImage(
          posterImgUrl.value,
          `邀请函_来源（${trackInfo.sourceName || ''}）${dayjs().format('YYYYMMDDHHmmss')}`,
        );
      } else {
        message.error('生成失败，来源不存在');
      }
    } catch (error) {
      console.log(error);
      message.error('生成失败，请重试');
    }
    resetInitialized();
    modalApi.lock(false);
    loading.value = false;
    // emit('reload');
    // modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
    loading.value = false;
  }
}

function reset() {
  posterImgUrl.value = '';
  qrcodeUrl.value = '';
  miniProQrcodeUrl.value = '';
  currTrackInfo.value = {};
}

async function handleClosed() {
  await formApi.resetForm();
  bgImgeUrl.value = '';
  reset();
  resetInitialized();
}
</script>

<template>
  <BasicModal title="生成图片" confirm-text="生成图片并下载">
    <BasicForm />
    <Spin :spinning="loading" tip="生成图片中...">
      <div v-if="!posterImgUrl" class="flex justify-center">
        <div
          v-if="currTrackInfo?.id"
          ref="captureRef"
          class="relative h-[800px] w-[400px]"
        >
          <img :src="bgImgeUrl" alt="" class="h-full w-full" />
          <div
            v-if="currTrackInfo.urlType === 1"
            class="absolute left-[292.5px] top-[687.5px]"
          >
            <QRCode :value="qrcodeUrl" :bordered="false" :size="77.5" />
          </div>
          <div
            v-if="currTrackInfo.urlType === 2"
            class="absolute left-[292.5px] top-[687.5px] h-[77.5px] w-[77.5px] overflow-hidden rounded-[100px]"
          >
            <img :src="miniProQrcodeUrl" class="h-full w-full" alt="" />
          </div>
        </div>
      </div>
      <div v-if="posterImgUrl" class="flex justify-center">
        <div class="relative h-[800px] w-[400px]">
          <img :src="posterImgUrl" class="h-full w-full" alt="" />
        </div>
      </div>
    </Spin>
  </BasicModal>
</template>
